home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4138 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  80 lines

  1. Path: gryphon.phoenix.net!usenet
  2. From: brucew@phoenix.net (Bruce Wedding)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: HELP!! BAMBOOZLED BEGINNER!!
  5. Date: Fri, 02 Feb 1996 03:28:31 GMT
  6. Organization: BranPaul Systems
  7. Message-ID: <4eru59$s8t@gryphon.phoenix.net>
  8. References: <Pine.OSF.3.91l.960130235948.20497A-100000@saul3.u.washington.edu>
  9. NNTP-Posting-Host: dial8.phoenix.net
  10. X-Newsreader: Moe's Newsreader    
  11.  
  12. >However, when I try to raise 5 to the 7th power, I get "12589" 
  13. >when it really should be "78125". My teacher told me that instead of using
  14. >plain 'int', I should use 'long int'. 
  15.  
  16. If your ints are 16 bits, your teacher is correct.  The upper
  17. limit of a 16 bit signed int is about 32,766.
  18.  
  19. >   int i,         /* integer */
  20. Since you aren't accepting negative values for the exponent, make
  21. this:
  22. unsigned long int i, i_total;  
  23. That will give the largest range without resorting to floating
  24. point.
  25.  
  26. >   scanf("%d", &i); 
  27.  
  28. change this to scanf("%U", &i);
  29.  
  30.   
  31. >    i_total = 1;       /* gives i_total an initial total of '1' */
  32.  
  33. >    for (count = 1;  count <= n;  count = count + 1){
  34. >        i_total = i_total * i;
  35. >    }
  36.  
  37. for (count = 0; count < n; count++)
  38. {
  39.     i_total *= i;
  40.  
  41. printf("%ul raised to the %dth power is %ul\n\n", i, n, i_total);
  42.  
  43. Here is a tested version.  There is still no overflow protection.
  44.  
  45. #include <stdio.h>
  46.  
  47. int main()
  48. {
  49.    unsigned long int i = 0, i_total = 0;
  50.    int power = 0, n = 0, scanned = 0;
  51.  
  52.    while (!scanned)
  53.    {
  54.       puts("Enter number");
  55.       scanned = scanf("%U*%c", &i);
  56.    }
  57.    scanned = 0;
  58.    while (!scanned)
  59.    {
  60.      puts("Enter exponent");
  61.      scanned = scanf("%U*%c", &power);
  62.    }
  63.    i_total = 1;       /* gives i_total an initial total of '1' */
  64.    for (n = 0; n < power; n++)
  65.       i_total *= i;
  66.    printf("%lu raised to the %dth power is %lu\n\n", i, n,
  67. i_total);
  68.    return 0;
  69. }
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76. Bruce D. Wedding                        Have Compiler, Will Travel!
  77.               Perspicacious Programming Performed Promptly
  78. Katy, Texas, USA, Planet Earth, Milkyway Galaxy, Known Universe
  79.  
  80.